import { useEffect, useRef, useState } from "react";

export const isFalsy = (value: unknown) => (value === 0 ? false : !value);

export const cleanObject = (obj: object) => {
  const _obj = { ...obj };
  Object.keys(_obj).forEach((o) => {
    // @ts-ignore
    const val = _obj[o];
    if (isFalsy(val)) {
      // @ts-ignore
      delete _obj[o];
    }
  });
  return _obj;
};

export const useMount = (callback: () => void) => {
  useEffect(() => {
    callback();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
};

export const useDebounce = <V>(value: V, delay?: number): any => {
  const [debounceValue, setDebounceValue] = useState(value);

  useEffect(() => {
    const time = setTimeout(() => {
      setDebounceValue(value);
    }, delay);
    return () => {
      clearTimeout(time);
    };
  }, [value, delay]);

  return debounceValue;
};

export const useArray = <T>(initialValue: T[]) => {
  const [value, setValue] = useState(initialValue);
  return {
    value,
    setValue,
    add: (item: T) => setValue([...value, item]),
    clear: () => setValue([]),
    removeIndex: (index: number) => {
      const copy = [...value];
      copy.splice(index, 1);
      setValue(copy);
    },
  };
};

// 动态文档标题
export const useDocumentTitle = (
  title: string,
  keepOnUnmount: boolean = true
) => {
  const oldTitle = useRef(document.title).current;

  useEffect(() => {
    document.title = title;
  }, [title]);

  useEffect(() => {
    return () => {
      if (!keepOnUnmount) {
        // 不更新成初始
        document.title = oldTitle;
      }
    };
  }, [oldTitle, keepOnUnmount]);
};

// 动态设置组件挂载状态
export const useMountRef = () => {
  const mountRef = useRef(false);

  useEffect(() => {
    mountRef.current = true;
    return () => {
      mountRef.current = false;
    };
  });

  return mountRef;
};
